<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="车牌号" v-bind="validateInfos.carNumber">
            <a-input v-model:value="formData.carNumber" placeholder="请输入车牌号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="泊位号" v-bind="validateInfos.berthNumber">
            <a-input v-model:value="formData.berthNumber" placeholder="请输入泊位号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="地址" v-bind="validateInfos.address">
            <a-textarea v-model:value="formData.address" :rows="4" placeholder="请输入地址" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="开始时间" v-bind="validateInfos.startTime">
            <a-date-picker
              placeholder="请选择开始时间"
              v-model:value="formData.startTime"
              showTime
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="结束时间" v-bind="validateInfos.endTime">
            <a-date-picker
              placeholder="请选择结束时间"
              v-model:value="formData.endTime"
              showTime
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="停车时长" v-bind="validateInfos.durationParking">
            <a-input v-model:value="formData.durationParking" placeholder="请输入停车时长" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="小时单价" v-bind="validateInfos.price">
            <a-input v-model:value="formData.price" placeholder="请输入小时单价" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="超1小时单价" v-bind="validateInfos.overOneHourprice">
            <a-input v-model:value="formData.overOneHourprice" placeholder="请输入超1小时单价" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="计费金额" v-bind="validateInfos.oldAmount">
            <a-input-number v-model:value="formData.oldAmount" placeholder="请输入计费金额" style="width: 100%" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实际金额" v-bind="validateInfos.actualAmount">
            <a-input-number v-model:value="formData.actualAmount" placeholder="请输入实际金额" style="width: 100%" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="出场状态" v-bind="validateInfos.getOutStatus">
            <j-dict-select-tag v-model:value="formData.getOutStatus" dictCode="get_out_status" placeholder="请选择出场状态" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="付款状态" v-bind="validateInfos.payStatus">
            <j-dict-select-tag v-model:value="formData.payStatus" dictCode="pay_status" placeholder="请选择付款状态" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="实付金额" v-bind="validateInfos.payamount">
            <a-input v-model:value="formData.payamount" placeholder="请输入实付金额" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../PaymentManagement.api';
  import { Form } from 'ant-design-vue';
  import { extractHours, timeDifference, totalCharge } from '/@/utils/util';
  import { getMallParkingSpaceList, saveOrUpdateForMallParking } from '../../MallParkingSpace/MallParkingSpace.api';
  import { sendMessageTest } from '../../system/message/template/template.api';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    carNumber: '',
    berthNumber: '',
    oldAmount: undefined,
    actualAmount: undefined,
    address: '',
    startTime: '',
    endTime: '',
    durationParking: 3,
    price: 5,
    getOutStatus: '',
    payStatus: '',
    payamount: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    carNumber: [{ required: true, message: '请输入车牌号!' }],
    berthNumber: [{ required: true, message: '请输入泊位号!' }],
    startTime: [{ required: true, message: '请输入开始时间!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  watch(
    () => formData.endTime,
    (val) => {
      if (val) {
        formData.durationParking = timeDifference(formData.startTime, val);
        const amount = totalCharge(formData.startTime, val, parseInt(formData.price || 5), parseInt(formData.overOneHourPrice || 3));
        formData.oldAmount = amount;
        formData.actualAmount = amount;
      }
    },
    {
      immediate: true,
    }
  );

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          if (isUpdate.value) {
            const params1 = {
              column: 'createTime',
              order: 'desc',
              pageNo: 1,
              pageSize: 1,
              number: formData.carNumber,
            };
            getMallParkingSpaceList(params1).then((res1) => {
              if (res1.records.length > 0) {
                const data = res1.records;
                saveOrUpdateForMallParking({ ...data[0], status: '1' }, true);
              }
            });
            if (formData.getOutStatus === '2') {
              const params2 = {
                msgType: 'system',
                receiver: model.createBy,
                templateCode: '车辆出场提示',
                templateContent: '当前车辆已出场，请尽快支付，如已支付请忽略！',
                templateName: '车辆出场提示',
              };
              sendMessageTest(params2);
            }

            const hours = extractHours(model.durationParking);
            if (hours > 10) {
              const params2 = {
                msgType: 'system',
                receiver: model.createBy,
                templateCode: '车辆处理提示',
                templateContent: '当前车辆已在停车场停车超过10小时，请在1小时内驶离，如未驶离将作为僵尸车处理！',
                templateName: '车辆处理提示',
              };
              sendMessageTest(params2);
            }
          }
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
